package com.example.taluo.controller;

import com.example.taluo.entity.dto.ResponseDO;
import com.example.taluo.security.TokenProvider;
import com.example.taluo.service.MatchmakingService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/matchmaking")
public class MatchmakingController {
    @Autowired
    private MatchmakingService matchmakingService;

    @Autowired
    private TokenProvider tokenProvider;

    // 加入匹配队列
    @PostMapping("/join")
    public ResponseDO joinMatchmaking(HttpServletRequest request) {
        String token = request.getHeader("Authorization").replace("Bearer ", "");
        String userId = tokenProvider.getUserIdFromToken(token);
        System.out.println("userid是" + userId);
        matchmakingService.joinQueue(Integer.parseInt(userId));
        return ResponseDO.success("已加入匹配队列");
    }

    // 查询匹配状态
    @GetMapping("/status")
    public ResponseDO getMatchmakingStatus(HttpServletRequest request) {
        try {
            String token = request.getHeader("Authorization").replace("Bearer ", "");
            String userId = tokenProvider.getUserIdFromToken(token);  // 从Token中获取用户ID
            Integer gameId = matchmakingService.checkMatchStatus(Integer.parseInt(userId));  // 检查匹配状态

            System.out.println("匹配状态查询，用户ID: " + userId + ", 游戏ID: " + gameId);

            if (gameId != null) {
                // 匹配成功，返回游戏ID
                return ResponseDO.success(Map.of("status", "matched", "gameId", gameId));
            } else {
                // 匹配中，返回等待状态
                return ResponseDO.success(Map.of("status", "waiting"));
            }
        } catch (Exception e) {
            // 捕获异常，返回错误信息
            return ResponseDO.fail("Failed to get matchmaking status", e.getMessage());
        }
    }
}
